package org.issaclu.springbootmybatis.util.mybatistypehandle;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.issaclu.springbootmybatis.user.enums.Sex;

import java.sql.*;
import java.util.Arrays;

public class SexTypeHandler implements TypeHandler<Sex> {
    @Override
    public void setParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.TINYINT);
        } else {
            ps.setShort(i, parameter.code);
        }
    }

    @Override
    public Sex getResult(ResultSet rs, String columnName) throws SQLException {
        short sex = rs.getShort(columnName);
        return Arrays.stream(Sex.values()).filter(v -> v.code == sex).findFirst().orElse(null);
    }

    @Override
    public Sex getResult(ResultSet rs, int columnIndex) throws SQLException {
        short sex = rs.getShort(columnIndex);
        return Arrays.stream(Sex.values()).filter(v -> v.code == sex).findFirst().orElse(null);
    }

    @Override
    public Sex getResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 不会出现在存储过程的语句中， 不用实现了
        return null;
    }
}
